package com.jams.goodox.activity.qa.teacher;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.activity.mine.buy.RecordNextStepActivity;
import com.jams.goodox.activity.mine.image.Util;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.activity.qa.entity.Teacher;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.listen.CustomShareListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by HP on 2018/8/8.
 *
 * 教师详情
 */

public class TeacherDetailActivity extends BaseActivity implements
        OnItemClickListener,LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange {

    private static final String TAG = "TeacherDetailActivity";
    public static String url ="http://mobile.umeng.com/social";
    @Bind(R.id.recycler_view)
    LFRecyclerView recyclerView;

    @Bind(R.id.nickname)
    TextView nickname;
    @Bind(R.id.answer_counts)
    TextView answer_counts;
    @Bind(R.id.descr)
    TextView descr;
    @Bind(R.id.headImage)
    SimpleDraweeView headImage;

    @Bind(R.id.ask)
    TextView ask;

    @Bind(R.id.ancounts)
    TextView ancounts;

//    private UMShareListener mShareListener;
//    private ShareAction mShareAction;

    private int page = 0;
    private CommonRecycleViewAdapter pAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what){
                case 1:
                    if (isRefresh) {
                        recyclerView.stopRefresh(status);
                        pAdapter.notifyDataSetChanged();
                    } else {
                        recyclerView.stopLoadMore();
                        pAdapter.notifyDataSetChanged();
                    }
                    break;

                case 2:
                    nickname.setText(question.getNickName());
                    answer_counts.setText(question.getId() + "个问答");

                    ancounts.setText("已回答(" +  question.getId() +")");

                    descr.setText(question.getDescr());
                    headImage.setImageURI(question.getImgPath());
                    break;
            }
        }
    };
    private List<Question> list = new ArrayList<>();

    private boolean status = false;//判断加载成功还是失败
    private boolean isRefresh = true;
    private int pageNum = 1;

    int teacherId;
    Question question;

    // IWXAPI 是第三方app和微信通信的openapi接口
    WXWebpageObject webpage;
    WXMediaMessage msg;
    SendMessageToWX.Req req;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tacherdetail;
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        Log.d("TTTTTT33","getNickName() = " + question.getNickName());
        TextObject textObject = new TextObject();
        textObject.text = "我正在使用好氧  " + BuildConfig.BASE_URL+
                "page/course/teacher?id=" + teacherId;
        textObject.title = TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName() ;
        textObject.actionUrl = url;

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        textObject.thumbData = baos.toByteArray();

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        textObject.thumbData = Util.bmpToByteArray(thumbBmp, true);

        return textObject;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    protected void init() {
        //StyleUtil.titleBackKey(this,"教师详情");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部


        StyleUtil.titleBothIconListener(this, "教师详情", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                },

                R.mipmap.icon_share_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        showSharePop(new CustomShareListener() {
                            @Override
                            public void onShareCallBack(int type) {

                                switch (type){
                                    case 1:
                                        Log.d("TTTTTT33","getNickName() = " + question.getNickName());
                                        webpage = new WXWebpageObject();
                                        webpage.webpageUrl = BuildConfig.BASE_URL+
                                                "page/course/teacher?id=" + teacherId;
                                        msg = new WXMediaMessage(webpage);
                                        msg.title = TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName();

                                        msg.description = /*TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName()*/" ";

//                                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.login_logo_icon);
//                                        msg.setThumbImage(bitmap);

                                        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                                        bmp.recycle();
                                        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

                                        req = new SendMessageToWX.Req();
                                        req.transaction = buildTransaction("webpage");
                                        req.message = msg;
                                        req.scene = SendMessageToWX.Req.WXSceneSession;
                                        api.sendReq(req);

                                        break;
                                    case 2:
                                        Log.d("TTTTTT33","getNickName() = " + question.getNickName());
                                        webpage = new WXWebpageObject();
                                        webpage.webpageUrl = BuildConfig.BASE_URL+
                                                "page/course/teacher?id=" + teacherId;
                                        msg = new WXMediaMessage(webpage);
                                        msg.title = TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName();
//                                        msg.description = TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName();
                                        msg.description = /*TextUtils.isEmpty(question.getNickName()) ? "好氧教师详情" : question.getNickName()*/" ";

//                                        Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//                                        msg.setThumbImage(bitmap2);

                                        Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                        Bitmap thumbBmp2 = Bitmap.createScaledBitmap(bmp2, THUMB_SIZE, THUMB_SIZE, true);
                                        bmp2.recycle();
                                        msg.thumbData = Util.bmpToByteArray(thumbBmp2, true);

                                        req = new SendMessageToWX.Req();
                                        req.transaction = buildTransaction("webpage");
                                        req.message = msg;
                                        req.scene = SendMessageToWX.Req.WXSceneTimeline;
                                        api.sendReq(req);
                                        break;

                                    case 3:
                                        WbShareHandler shareHandler = new WbShareHandler(TeacherDetailActivity.this);
                                        shareHandler.registerApp();
                                        shareHandler.setProgressColor(getResources().getColor(R.color.main_background));

                                        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                                        weiboMessage.textObject = getTextObj();

                                        shareHandler.shareMessage(weiboMessage, true);
//                                        WeiboPageUtils.getInstance(SimpleHtmlActivity.this,authInfo).shareToWeibo("哈哈哈哈哈",useWeb);
                                        break;

                                    case 4:
                                        ClipboardManager cm = (ClipboardManager)
                                                getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 将文本内容放到系统剪贴板里。
                                        cm.setText(BuildConfig.BASE_URL +
                                                "page/course/teacher?id=" + teacherId);
                                        ToastUtil.show("复制成功");
                                        break;
                                    default:
                                        break;
                                }
                            }

                        });

                    }
                });

        teacherId = getIntent().getIntExtra("teacherId",-1);

        ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SePref.isLogin()){
                    Intent intent = new Intent(TeacherDetailActivity.this,AskHeActivity.class);
                    intent.putExtra("teacherId",teacherId);
                    startActivity(intent);
                }else {
                    ToastUtil.show("请先登录!");
                }

            }
        });


        recyclerView.setLoadMore(true);
        recyclerView.setRefresh(true);
        //recyclerView.setNoDateShow();
        recyclerView.setAutoLoadMore(true);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setLFRecyclerViewListener(this);
        recyclerView.setScrollChangeListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        pAdapter = new CommonRecycleViewAdapter(recyclerView,list,R.layout.question_item) {
            @Override
            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {

                Question question = (Question) item;
                holder.setText(R.id.nickName,question.getNickName());
                holder.loadImage(R.id.logo,question.getImgPath());
                holder.setText(R.id.conent,question.getDescr());
                holder.setText(R.id.type,"查看答案");
                holder.setText(R.id.createTime, TimeUtils.getDateToString(question.getCreateTime()));
            }


        };

        recyclerView.setFootText("");
        recyclerView.setAdapter(pAdapter);

        requestData();

        teacherPublic();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    //api/teacher/home
    public void requestData() {
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("teacherId:" + teacherId)
//                .append(",pageNum:" + pageNum)
//                .append(",pageSize:" + 10)
        ;
        params.put("requestData", "{" + pData.toString() + "}");
        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);

        Call<ResponseBody> example = createCallService(LoginService.class).tacherHome(body);

        showLoading();
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, " data home= " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if (200 == jsonObject.getInt("code")) {
                        String responseData = jsonObject.getString("responseData");
                        JSONObject jsonObject1 = new JSONObject(responseData);
                        question = new Question();
                        question.setNickName(jsonObject1.getString("nickName"));
                        question.setId(jsonObject1.getInt("questionNum"));
                        question.setDescr(jsonObject1.getString("individualitySign"));
                        question.setImgPath(jsonObject1.getString("imgPath"));
                        mHandler.sendEmptyMessage(2);

                    } else {
                        ToastUtil.show("网络异常！");
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG, "onFailure = " + t.getMessage());
            }
        });

    }


    //api/question/teacherPublic
    public void teacherPublic() {
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("memberId:" + teacherId)
                .append(",pageNum:" + pageNum)
                .append(",pageSize:" + 10)
        ;

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);

        Log.d(TAG, " data strEntity= " + strEntity);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);

        Call<ResponseBody> example = createCallService(LoginService.class).teacherPublic(body);

        showLoading();
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, " data teacherPublic= " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if (200 == jsonObject.getInt("code")) {
                        status = true;
                        if (isRefresh) {
                            list.clear();
                        }
                        String responseData = jsonObject.getString("responseData");
                        JSONArray jsonArray = new JSONArray(responseData);
                        if (null == jsonArray || jsonArray.length() <= 0) {
                            //ToastUtil.show("没有更多数据");
                            mHandler.sendEmptyMessage(1);
                            return;
                        }

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            Question teacher = new Question();
                            teacher.setImgPath(object.getString("imgPath"));
                            teacher.setId(object.getInt("id"));
                            teacher.setDescr(object.getString("descr"));
                            teacher.setNickName(object.getString("nickName"));
                            teacher.setQueState(object.getInt("queState"));
                            teacher.setCreateTime(object.getLong("createTime"));

                            Log.d(TAG, "teacher = " + teacher.toString());
                            list.add(teacher);
                        }
                        //mHandler.sendEmptyMessage(1);
                        //pAdapter.notifyDataSetChanged();

                    } else {
                        status = false;
                        ToastUtil.show("网络异常！");
                    }
                } catch (Exception e) {
                    status = false;
                    ToastUtil.show("Exception:" + e.getMessage());
                }

                mHandler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                status = false;
                mHandler.sendEmptyMessage(1);
                Log.d(TAG, "onFailure = " + t.getMessage());
            }
        });

    }

    @Override
    public void onClick(int position) {

        Intent intent = new Intent(this,TeacherAnswerQuestionDetailActivity.class);
        intent.putExtra("question",list.get(position));
        startActivity(intent);
    }

    @Override
    public void onLongClick(int po) {

    }

    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        isRefresh = true;

        teacherPublic();
    }

    @Override
    public void onLoadMore() {
        pageNum ++;
        isRefresh = false;
        teacherPublic();
    }

}
